<template>
  <div class="table-recognizer">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="input-card">
          <template #header>
            <div class="card-header">
              <span>上传图片</span>
              <el-button 
                type="primary" 
                @click="recognizeTable" 
                :disabled="!inputImage"
              >
                识别表格
              </el-button>
            </div>
          </template>
          <div
            class="upload-area"
            @drop.prevent="handleDrop"
            @dragover.prevent
            @click="triggerUpload"
          >
            <input
              type="file"
              ref="fileInput"
              style="display: none"
              accept="image/*"
              @change="handleFileChange"
            />
            <div v-if="!inputImage" class="upload-placeholder">
              <el-icon><Upload /></el-icon>
              <div>点击或拖拽包含表格的图片到此处</div>
            </div>
            <img v-else :src="inputImage" class="preview-image" />
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="output-card">
          <template #header>
            <div class="card-header">
              <span>识别结果</span>
              <div class="controls">
                <el-select 
                  v-model="outputFormat" 
                  placeholder="选择导出格式"
                  style="width: 120px"
                >
                  <el-option label="Excel" value="excel" />
                  <el-option label="Word" value="word" />
                  <el-option label="HTML" value="html" />
                </el-select>
                <el-button 
                  type="primary" 
                  @click="downloadResult" 
                  :disabled="!recognitionResult"
                >
                  导出结果
                </el-button>
              </div>
            </div>
          </template>
          <div 
            class="result-area" 
            v-html="recognitionResult || '识别结果将显示在这里'"
          ></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'

const fileInput = ref(null)
const inputImage = ref('')
const recognitionResult = ref('')
const outputFormat = ref('excel')

const triggerUpload = () => {
  fileInput.value.click()
}

const handleFileChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    processImage(file)
  }
}

const handleDrop = (event) => {
  const file = event.dataTransfer.files[0]
  if (file && file.type.startsWith('image/')) {
    processImage(file)
  } else {
    ElMessage.error('请上传图片文件')
  }
}

const processImage = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    inputImage.value = e.target.result
  }
  reader.readAsDataURL(file)
}

const recognizeTable = async () => {
  try {
    // 将 base64 转换为文件对象
    const response = await fetch(inputImage.value)
    const blob = await response.blob()
    const file = new File([blob], 'image.jpg', { type: blob.type })

    // 创建 FormData
    const formData = new FormData()
    formData.append('image', file)

    // 调用后端识别 API
    const res = await fetch('http://localhost:5000/api/recognize-table', {
      method: 'POST',
      body: formData
    })

    if (!res.ok) {
      throw new Error('识别失败')
    }

    const data = await res.json()
    if (data.success) {
      recognitionResult.value = data.html
      ElMessage.success('识别成功')
    } else {
      throw new Error(data.error || '识别失败')
    }
  } catch (error) {
    console.error('识别失败:', error)
    ElMessage.error('识别失败: ' + error.message)
  }
}

const downloadResult = async () => {
  if (!recognitionResult.value) return

  try {
    let url = ''
    let filename = ''

    // 根据选择的格式调用不同的导出 API
    if (outputFormat.value === 'excel') {
      url = 'http://localhost:5000/api/export-excel'
      filename = 'table.xlsx'
    } else if (outputFormat.value === 'word') {
      url = 'http://localhost:5000/api/export-word'
      filename = 'table.docx'
    } else {
      // HTML 格式直接下载当前内容
      const blob = new Blob([recognitionResult.value], { type: 'text/html' })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = 'table.html'
      link.click()
      URL.revokeObjectURL(url)
      return
    }

    // 调用导出 API
    const res = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ html: recognitionResult.value })
    })

    if (!res.ok) {
      throw new Error('导出失败')
    }

    // 下载文件
    const blob = await res.blob()
    const downloadUrl = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = downloadUrl
    link.download = filename
    link.click()
    URL.revokeObjectURL(downloadUrl)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败: ' + error.message)
  }
}
</script>

<style scoped>
.table-recognizer {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.upload-area {
  height: 400px;
  border: 2px dashed var(--el-border-color);
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: var(--el-color-primary);
}

.upload-placeholder {
  text-align: center;
  color: var(--el-text-color-secondary);
}

.upload-placeholder .el-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.preview-image {
  max-width: 100%;
  max-height: 400px;
  object-fit: contain;
}

.result-area {
  height: 400px;
  padding: 20px;
  overflow: auto;
}

:deep(table) {
  border-collapse: collapse;
  width: 100%;
}

:deep(th), :deep(td) {
  padding: 8px;
  text-align: left;
  border: 1px solid var(--el-border-color);
}
</style> 